package com.china08.yxyapi.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

// import com.aspose.email.system.exceptions.ArgumentException;
import com.aspose.words.Bookmark;
import com.aspose.words.BreakType;
import com.aspose.words.CellVerticalAlignment;
import com.aspose.words.CompositeNode;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.License;
import com.aspose.words.LineStyle;
import com.aspose.words.Node;
import com.aspose.words.NodeImporter;
import com.aspose.words.NodeType;
import com.aspose.words.Orientation;
import com.aspose.words.PageVerticalAlignment;
import com.aspose.words.PaperSize;
import com.aspose.words.Paragraph;
import com.aspose.words.ParagraphAlignment;
import com.aspose.words.PreferredWidth;
import com.aspose.words.SaveFormat;
import com.aspose.words.Section;
import com.aspose.words.Table;
import com.aspose.words.TableAlignment;
import com.aspose.words.net.System.Data.DataTable;

@Component
public class WordUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(WordUtil.class);

    public int Docversion = 2007;
    private DocumentBuilder oWordApplic; // a reference to Word application
    private Document oDoc; // a reference to the document
    private static InputStream license;

    /**
     * 获取license
     * 
     * @return
     */
    public static boolean getLicense(String filepath) {
        boolean result = false;
        try {
            // ClassLoader loader =
            // Thread.currentThread().getContextClassLoader();
            // license = new
            // FileInputStream(loader.getResource("Aspose.Words.lic").getPath());//

            // File file = new File("Aspose.Words.lic");
            // if (!file.exists()) {
            // file = new File("config/Aspose.Words.lic");
            // }
            //
            // Resource resource = new FileSystemResource(file);
            // ResourceLoaderClassLoadHelper resourceLoader = new
            // ResourceLoaderClassLoadHelper();
            // if (resource.exists()) {
            // resourceLoader.getResource("classpath:Aspose.Words.lic");
            // }

            // 凭证文件
            // license =
            // ClassLoader.getSystemResourceAsStream("classpath:Aspose.Words.lic");

            File file2 = new File(filepath + File.separator + "license.xml");
            // File file = ResourceUtils.getFile("classpath:Aspose.Words.lic");
            license = new FileInputStream(file2);
            License aposeLic = new License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            LOGGER.error("========================获取凭证文件异常" + e);
            e.printStackTrace();
        }
        return result;
    }

    // public void OpenWithTemplate(String strFileName) throws Exception {
    // if (!getLicense()) { return; }
    // if (!StringUtils.isNotBlank(strFileName)) {
    // oDoc = new Document(strFileName);
    // }
    // }

    public void Open(String filepath) throws Exception {
        if (!getLicense(filepath)) { return; }
        oDoc = new Document();
    }

    public void Builder() throws Exception {
        oWordApplic = new DocumentBuilder(oDoc);
    }

    /// 保存文件
    public void SaveAs(String strFileName) throws Exception {
        if (this.Docversion == 2007) {
            oDoc.save(strFileName, SaveFormat.DOCX);
        } else {
            oDoc.save(strFileName, SaveFormat.DOC);
        }
    }

    /// 添加内容
    public void InsertText(String strText, double conSize, boolean conBold, String conAlign) throws Exception {
        oWordApplic.setBold(conBold);
        oWordApplic.getFont().setSize(conSize);
        switch (conAlign) {
        case "left":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        case "center":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            break;
        case "right":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
            break;
        default:
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        }
        oWordApplic.writeln(strText);
    }

    public void InsertHtml(String strText, double conSize, boolean conBold, String conAlign) throws Exception {
        oWordApplic.setBold(conBold);
        oWordApplic.getFont().setSize(conSize);
        switch (conAlign) {
        case "left":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        case "center":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            break;
        case "right":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
            break;
        default:
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        }
        oWordApplic.insertHtml(strText, true);
    }

    /// 添加内容
    public void WriteText(String strText, double conSize, boolean conBold, String conAlign) throws Exception {
        oWordApplic.setBold(conBold);
        oWordApplic.getFont().setSize(conSize);
        switch (conAlign) {
        case "left":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        case "center":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            break;
        case "right":
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
            break;
        default:
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            break;
        }
        oWordApplic.write(strText);
    }

    // region 设置纸张
    public void setPaperSize(String papersize) {
        switch (papersize) {
        case "A4":
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.A4);
                section.getPageSetup().setOrientation(Orientation.PORTRAIT);
                section.getPageSetup().setVerticalAlignment(PageVerticalAlignment.TOP);
            }
            break;
        case "A4H":// A4横向
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.A4);
                section.getPageSetup().setOrientation(Orientation.LANDSCAPE);
                section.getPageSetup().getTextColumns().setCount(2);
                section.getPageSetup().getTextColumns().setEvenlySpaced(true);
                section.getPageSetup().getTextColumns().setLineBetween(true);
            }
            break;
        case "A3":
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.A3);
                section.getPageSetup().setOrientation(Orientation.PORTRAIT);
            }
            break;
        case "A3H":// A3横向
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.A3);
                section.getPageSetup().setOrientation(Orientation.LANDSCAPE);
                section.getPageSetup().getTextColumns().setCount(2);
                section.getPageSetup().getTextColumns().setEvenlySpaced(true);
                section.getPageSetup().getTextColumns().setLineBetween(true);
            }
            break;
        case "16K":
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.B5);
                section.getPageSetup().setOrientation(Orientation.PORTRAIT);
            }
            break;
        case "B4H":
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPaperSize(PaperSize.B4);
                section.getPageSetup().setOrientation(Orientation.LANDSCAPE);
                section.getPageSetup().getTextColumns().setCount(2);
                section.getPageSetup().getTextColumns().setEvenlySpaced(true);
                section.getPageSetup().getTextColumns().setLineBetween(true);
            }
            break;
        case "8KH":
            for (Section section : oDoc.getSections()) {
                section.getPageSetup().setPageWidth(Double.parseDouble("36.4"));
                section.getPageSetup().setPageHeight(Double.parseDouble("25.7"));
                section.getPageSetup().setOrientation(Orientation.LANDSCAPE);
                section.getPageSetup().getTextColumns().setCount(2);
                section.getPageSetup().getTextColumns().setEvenlySpaced(true);
                section.getPageSetup().getTextColumns().setLineBetween(true);
            }
            break;
        }
    }

    public void SetHeade(String strBookmarkName, String text) throws Exception {
        if (oDoc.getRange().getBookmarks().get(strBookmarkName) != null) {
            Bookmark mark = oDoc.getRange().getBookmarks().get(strBookmarkName);
            mark.setText(text);
        }
    }

    /// 插入word内容
    public static void InsertDocument(Node insertAfterNode, Document mainDoc, Document srcDoc) throws Exception {
        // Make sure that the node is either a pargraph or table.
        if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH) & (insertAfterNode.getNodeType() != NodeType.TABLE))
            throw new Exception("The destination node should be either a paragraph or table.");

        // We will be inserting into the parent of the destination paragraph.
        CompositeNode dstStory = insertAfterNode.getParentNode();

        // Remove empty paragraphs from the end of document
        while (null != srcDoc.getLastSection().getBody().getLastParagraph()
                && !srcDoc.getLastSection().getBody().getLastParagraph().hasChildNodes()) {
            srcDoc.getLastSection().getBody().getLastParagraph().remove();
        }
        NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);

        // Loop through all sections in the source document.
        int sectCount = srcDoc.getSections().getCount();
        for (int sectIndex = 0; sectIndex < sectCount; sectIndex++) {
            Section srcSection = srcDoc.getSections().get(sectIndex);
            // Loop through all block level nodes (paragraphs and tables) in the
            // body of the section.
            int nodeCount = srcSection.getBody().getChildNodes().getCount();
            for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) {
                Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
                Node newNode = importer.importNode(srcNode, true);
                dstStory.insertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }

    static void InsertDocument(Node insertAfterNode, Document srcDoc) throws Exception {
        // Make sure that the node is either a paragraph or table.
        if (!(insertAfterNode.getNodeType() == NodeType.PARAGRAPH)
                && (!(insertAfterNode.getNodeType() == NodeType.TABLE)))
            throw new Exception("The destination node should be either a paragraph or table.");

        // We will be inserting into the parent of the destination paragraph.
        CompositeNode dstStory = insertAfterNode.getParentNode();

        // This object will be translating styles and lists during the import.
        NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.getDocument(),
                ImportFormatMode.KEEP_SOURCE_FORMATTING);

        // Loop through all sections in the source document.
        for (Section srcSection : srcDoc.getSections()) {
            // Loop through all block level nodes (paragraphs and tables) in the
            // body of the section.
            for (Node srcNode : srcSection.getBody()) {
                // Let's skip the node if it is a last empty paragraph in a
                // section.
                if (srcNode.getNodeType() == NodeType.PARAGRAPH) {
                    Paragraph para = (Paragraph) srcNode;
                    if (para.isEndOfSection() && !para.hasChildNodes()) continue;
                }
                // This creates a clone of the node, suitable for insertion into
                // the destination document.
                Node newNode = importer.importNode(srcNode, true);
                // Insert new node after the reference node.
                dstStory.insertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }

    /// 换行
    public void InsertLineBreak() throws Exception {
        oWordApplic.insertBreak(BreakType.LINE_BREAK);
    }

    /// 换多行
    public void InsertLineBreak(int nline) throws Exception {
        for (int i = 0; i < nline; i++)
            oWordApplic.insertBreak(BreakType.LINE_BREAK);
    }

    // region InsertScoreTable
    public boolean InsertScoreTable(boolean dishand, boolean distab, String handText) {
        try {
            oWordApplic.startTable();// 开始画Table
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            // 添加Word表格
            oWordApplic.insertCell();
            oWordApplic.getCellFormat().setWidth(115.0);
            oWordApplic.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(115));
            oWordApplic.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
            oWordApplic.startTable();// 开始画Table
            oWordApplic.getRowFormat().setHeight(20.2);
            oWordApplic.insertCell();
            oWordApplic.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
            oWordApplic.getFont().setSize(10.5);
            oWordApplic.setBold(false);
            oWordApplic.getFont().setSize(10.5);
            oWordApplic.setBold(false);
            oWordApplic.write("评卷人");

            oWordApplic.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            oWordApplic.getCellFormat().setWidth(50.0);

            oWordApplic.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(50));
            oWordApplic.getRowFormat().setHeight(20.0);
            oWordApplic.insertCell();

            oWordApplic.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
            oWordApplic.getFont().setSize(10.5);
            oWordApplic.setBold(false);
            oWordApplic.write("得分");

            oWordApplic.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            oWordApplic.getCellFormat().setWidth(50.0);

            oWordApplic.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(50));
            oWordApplic.endRow();

            oWordApplic.getRowFormat().setHeight(25.0);
            oWordApplic.insertCell();
            oWordApplic.getRowFormat().setHeight(25.0);
            oWordApplic.insertCell();
            oWordApplic.endRow();
            oWordApplic.endTable();

            oWordApplic.insertCell();

            oWordApplic.getCellFormat().setWidth(300.0);
            oWordApplic.getCellFormat().setPreferredWidth(PreferredWidth.AUTO);
            oWordApplic.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);

            oWordApplic.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); // 垂直居中对齐
            oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            oWordApplic.getFont().setSize(11);
            oWordApplic.setBold(true);
            oWordApplic.write(handText);
            oWordApplic.endRow();
            oWordApplic.getRowFormat().setHeight(28);
            oWordApplic.endTable();
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    // region 插入表格
    public boolean InsertTable(DataTable dt, boolean haveBorder) throws Exception {
        Table table = oWordApplic.startTable();// 开始画Table
        int paragraphAlignmentValue = oWordApplic.getParagraphFormat().getAlignment();
        oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        // 添加Word表格
        for (int row = 0; row < dt.getRows().getCount(); row++) {
            oWordApplic.getRowFormat().setHeight(25);
            for (int col = 0; col < dt.getColumns().getCount(); col++) {
                oWordApplic.insertCell();
                oWordApplic.getFont().setSize(10.5);
                oWordApplic.getFont().setName("宋体");
                oWordApplic.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); // 垂直居中对齐
                oWordApplic.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);// 水平居中对齐
                oWordApplic.getCellFormat().setWidth(50.0);
                oWordApplic.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(50));
                if (haveBorder == true) {
                    // 设置外框样式
                    oWordApplic.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
                    // 样式设置结束
                }
                oWordApplic.write(dt.getRows().get(row).get(col).toString());
            }
            oWordApplic.endRow();
        }
        oWordApplic.endTable();
        oWordApplic.getParagraphFormat().setAlignment(paragraphAlignmentValue);
        table.setAlignment(TableAlignment.CENTER);
        table.setPreferredWidth(PreferredWidth.AUTO);
        return true;
    }

    public void InsertPagebreak() throws Exception {
        oWordApplic.insertBreak(BreakType.PAGE_BREAK);
    }

    public void InsertBookMark(String BookMark) throws Exception {
        oWordApplic.startBookmark(BookMark);
        oWordApplic.endBookmark(BookMark);
    }

    public void GotoBookMark(String strBookMarkName) throws Exception {
        oWordApplic.moveToBookmark(strBookMarkName);
    }

    public void ClearBookMark() throws Exception {
        oDoc.getRange().getBookmarks().clear();
    }

    public void ReplaceText(String oleText, String newText) throws Exception {
        oDoc.getRange().replace(oleText, newText, false, false);
    }
}